<script setup lang="ts">
import { userAPI } from "@/api/user";
import { dataFormat } from "@/utils/dataFormatting";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";

interface UserInfo {
  id: string;
  username: string;
  nickname: string;
  avatar: string;
  email: string;
}
// 定义当前用户
const userSelf = ref<{ id: string; nickname: string } | null>(null);
// 定义表单数据模型
const query = ref("");
// 搜索结果
const result = ref<UserInfo>({} as UserInfo);
// 判断是否显示搜索结果
const showResult = ref(false);
// 是否开始加载
const isLoading = ref(false);
// 好友申请内容
const content = ref("");
// 查询
const onSubmit = async () => {
  if (query.value.trim() === "") {
    ElMessage({
      type: "warning",
      message: "搜索项不能为空",
      duration: 800,
    });
    return;
  }
  try {
    isLoading.value = true;
    const res = await userAPI.queryUser(query.value);
    result.value = res.data;
    content.value = "";
  } catch (error) {
    console.log("查询用户失败", error);
  } finally {
    showResult.value = true;
    isLoading.value = false;
  }
};
// 处理输入事件
const handleInput = () => {
  if (query.value.trim() === "") {
    showResult.value = false;
    result.value = {} as UserInfo;
    content.value = "";
  }
};
// 添加好友
const handleAddFriend = async () => {
  try {
    const userSelf = await window.electronAPI.store.get("user");
    const status = await window.electronAPI.wsGetStatus();
    if (status === "已连接") {
      const requestData = {
        type: "friendRequest",
        toUserId: result.value.id,
        content: content.value || "申请添加好友",
      };
      // 通过主进程发送好友请求
      const res = await window.electronAPI.wsSend(requestData);
      content.value = "";
      console.log("添加好友 -> 发送好友请求:", dataFormat(res));
    }
  } catch (err) {
    console.log("添加好友失败", err);
  }
};
onMounted(async () => {
  const user = await window.electronAPI.store.get("user");
  userSelf.value = user;
});
</script>

<template>
  <div class="container">
    <el-form :inline="true" class="form" @submit.prevent>
      <el-form-item class="form-item">
        <el-input
          v-model="query"
          placeholder="请输入用户名或邮箱"
          clearable
          :prefix-icon="Search"
          @input="handleInput"
          @keyup.enter="onSubmit"
        />
      </el-form-item>
      <el-form-item class="form-item">
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>
    <div
      style="height: 100%"
      v-loading="isLoading"
      :element-loading-background="'rgba(255, 255, 255, 0.2)'"
      v-if="showResult"
    >
      <div class="content" v-if="Object.keys(result).length > 0">
        <div class="info">
          <div class="avatar">
            <img :src="result.avatar" />
          </div>
          <div class="item">
            <div class="nickname">{{ result.nickname }}</div>
            <div class="username">用户名：{{ result.username }}</div>
            <div class="email">邮箱：{{ result.email }}</div>
          </div>
        </div>
        <div class="note" v-if="userSelf?.id !== result.id">
          <el-input
            v-model="content"
            placeholder="申请内容"
            type="textarea"
            clearable
          />
        </div>
        <div class="add-user" v-if="userSelf?.id !== result.id">
          <el-button type="primary" @click="handleAddFriend"
            >添加好友</el-button
          >
        </div>
      </div>
      <div class="empty" v-else>暂无搜索结果</div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f2f3f9;
  .form {
    margin-top: 10px;
    width: 100%;
    // 自适应高度
    height: fit-content;
    .form-item {
      &:nth-child(1) {
        margin-left: 20px;
        width: 60%;
      }
      &:nth-child(2) {
        width: 20%;
        margin-left: -10px;
        button {
          width: 100%;
        }
      }
    }
  }
  .content {
    border: 1px solid #dcdfe6;
    margin: 20px;
    border-radius: 10px;
    background: #fff;
    .info {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin: 18px;
      height: 80px;
      border-bottom: 1px solid #ccc;
      .avatar {
        margin-right: 18px;
        width: 60px;
        height: 60px;
        img {
          width: 100%;
          height: 100%;
          border-radius: 6px;
        }
      }
      .item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        font-size: 14px;
        color: #464a52;
        .nickname {
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
    .add-user {
      margin-bottom: 18px;
    }
    .note {
      margin: 10px auto;
      width: 90%;
      height: 100%;
      &:deep(.el-textarea__inner) {
        height: 100% !important;
        background-color: #f8f8f8; /* 浅蓝色背景 */
        // 移除文本域右下角的显示
        resize: none;
      }
    }
  }
  .empty {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: 14px;
    color: #909399;
  }
}
</style>